import os
import requests
import shutil
import json
import pyzipper
import vicent_pwd
from bs4 import BeautifulSoup

def get_weather():
    weather_r = requests.get("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%A4%A9%E6%B0%94")
    if weather_r.status_code!=200:
        return "fail"
    else:
        soup = BeautifulSoup(weather_r.content.decode("utf-8"), 'html.parser')
        w_elements = soup.find_all(class_="cu-mr-base")[0]
        weather = w_elements.get_text()
        return weather
def read_jsonFile(file):
    with open(file,"r")as f:
        return json.load(f)
def write_jsonFile(file,data):
    with open(file,"w")as f:
        json.dump(data,f)
def download_char(char_key):
    real_key = "webChar_"+char_key
    if os.path.exists("char/"+real_key):
        shutil.rmtree("char/"+real_key)
    
    chars_data = read_jsonFile("char/chars.json")
    inf_r = requests.get("http://127.0.0.1:8001/content/get/wpp_char?cid="+char_key)
    if inf_r.status_code!=200:
        return {"success":False,"msg":"网络错误，获取信息失败"}
    inf_data = json.loads(str(inf_r.content,"utf-8"))
    inf_data=inf_data["data"][0]
    print(inf_data)
    # while True:
    #     if real_key in chars_data:
    #         real_key+="-1"
    #     else:
    #         break

    file_r = requests.get("http://127.0.0.1:8001/files/get/"+inf_data["content"]["pack"]+"/")
    if file_r.status_code!=200:
        return {"success":False,"msg":"网络错误，获取文件失败"}
    if os.path.exists("char/"+real_key):
        shutil.rmtree("char/"+real_key)
    os.makedirs("char/"+real_key)
    with open("char/"+real_key+"/dl_"+real_key+".zip","wb")as f:
        f.write(file_r.content)
    with pyzipper.AESZipFile("char/"+real_key+"/dl_"+real_key+".zip") as zf:
        zf.setpassword(vicent_pwd.get_pwd("wpp").encode('utf-8'))
        zf.extractall("char/"+real_key)
    # with zipfile.ZipFile("char/"+real_key+"/dl_"+real_key+".zip", 'r') as zip_ref:
    #     zip_ref.extractall("char/"+real_key)
    os.remove("char/"+real_key+"/dl_"+real_key+".zip")
    char_data = read_jsonFile("char/"+real_key+"/char_inf.json")
    chars_dump_data = {
        "name": inf_data["title"],
        "key_name": real_key,
        "banner": char_data["banner"],
        "introduce": inf_data["content"]["introduce"],
        "create_local": False,
        "v": inf_data["content"]["v"],
        "net_id": inf_data["id"]
    }
    char_data["char_id"]=real_key
    chars_data[real_key]=chars_dump_data
    write_jsonFile("char/"+real_key+"/char_inf.json",char_data)
    write_jsonFile("char/chars.json",chars_data)